package com.config;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.pojo.User;
import com.util.Constant;

/**自定义拦截器
 * */
@Configuration
public class Interceptor implements HandlerInterceptor {
	
	private static final Logger logger = LoggerFactory.getLogger(Interceptor.class);

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String url = request.getRequestURL().toString();
		logger.info("URL:"+url);
		if(url.contains("error")) {
			response.sendRedirect("error");
			return true;
		}
		User user = (User) request.getSession().getAttribute(Constant.USER_SESSION);
		System.out.println("User Session : "+user);
		if(user == null) {
			response.sendRedirect("login");
			return false;
		}
		return true;
		//return HandlerInterceptor.super.preHandle(request, response, handler);
	}
	
}
